import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const shoppingCart = {
  state: {
    cartShopData: [],
    shoppingCart: [],
    subtotal: 0,
	table: null,
	dineStyle: null,
	addrId: null
  },
  mutations: {
    addToCart(state, item) {
      // 将商品添加到购物车数组
      state.shoppingCart.push(item);
    },
    removeFromCart(state, item) {
      // 从购物车数组中移除指定商品
      const index = state.shoppingCart.findIndex(cartItem => cartItem.id === item.id);
      if (index !== -1) {
        state.shoppingCart.splice(index, 1);
      }
    },
    updateSubtotal(state) {
      // 更新总价
      let subtotal = 0;
      state.shoppingCart.forEach(item => {
        subtotal += item.price * item.goodNum;
		// console.log(item)
      });
      state.subtotal = subtotal;
    },
    updateGoodNum(state, { itemId, childItemId, num }) {
      // 更新商品数量
      state.cartShopData.forEach(itemWrap => {
        if (itemWrap.id === itemId) {
          itemWrap.children.forEach(childItem => {
            if (childItem.id === childItemId) {
              childItem.goodNum = num;
            }
          });
        }
      });
    },
    updateCartShopData(state, updatedData) {
      // 更新菜品数据
      state.cartShopData = updatedData;
    },
	updateTableData(state, table) {
	  // 更新桌位
	  state.table = table;
	},
	updateShoppingCart(state, shoppingCart) {
	  // 更新购物车
	  state.shoppingCart = shoppingCart;
	},
	updateDineStyle(state, dineStyle) {
		// 更新就餐方式
		state.dineStyle = dineStyle;
	},
	updateAddrId(state, addrId) {
	  // 更新地址
	  state.addrId = addrId;
	},
  },
  actions: {
    addToCart({ commit }, item) {
      commit('addToCart', item);
      commit('updateSubtotal');
    },
    removeFromCart({ commit }, item) {
      commit('removeFromCart', item);
      commit('updateSubtotal');
    },
    updateGoodNum({ commit }, { itemId, childItemId, num }) {
      commit('updateGoodNum', { itemId, childItemId, num });
      commit('updateSubtotal');
    },
	updateCartShopData({ commit }, updatedData) {
	commit('updateCartShopData', updatedData);
	},
	updateTableData({ commit }, table) {
	commit('updateTableData', table);
	},	
	updateShoppingCart({ commit }, shoppingCart) {
	  commit('updateShoppingCart', shoppingCart);
	},
	updateDineStyle({ commit }, dineStyle) {
		commit('updateDineStyle', dineStyle);
	},
	updateAddrId({ commit }, addrId) {
		commit('updateAddrId', addrId);
	},
  }
}

export default shoppingCart